package com.sssre.lttcloud.framework.aspect;

import com.sssre.lttcloud.framework.annotation.PerformanceMonitor;
import com.sssre.lttcloud.framework.service.PerformanceMonitorService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 性能监测切面
 */
@Aspect
@Component
public class PerformanceMonitorAspect {

    @Autowired
    private PerformanceMonitorService performanceMonitorService;

    @Around("@annotation(com.sssre.lttcloud.framework.annotation.PerformanceMonitor)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        
        // 获取方法信息
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        PerformanceMonitor monitor = method.getAnnotation(PerformanceMonitor.class);
        
        // 记录方法调用开始
        String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName();
        String description = monitor.description().isEmpty() ? methodName : monitor.description();
        
        performanceMonitorService.recordMethodStart(methodName, description, 
            monitor.logParams() ? joinPoint.getArgs() : null);
        
        Object result = null;
        boolean success = true;
        String errorMessage = null;
        
        try {
            result = joinPoint.proceed();
            
            // 检查是否超时
            long executionTime = System.currentTimeMillis() - startTime;
            if (executionTime > monitor.timeout()) {
                performanceMonitorService.recordTimeout(methodName, executionTime, monitor.timeout());
            }
            
            return result;
        } catch (Exception e) {
            success = false;
            errorMessage = e.getMessage();
            throw e;
        } finally {
            // 记录方法调用结束
            long executionTime = System.currentTimeMillis() - startTime;
            performanceMonitorService.recordMethodEnd(methodName, executionTime, success, errorMessage,
                monitor.logResult() ? result : null);
        }
    }
} 